package com.GamersCom.db;

import java.sql.*;

/**
 * A connection manager designed to handle connections to data source 
 * @author Frank Sun
 *
 */

public class ConnMgr
{
	// create the Singleton variable
	private static ConnMgr connMgr = null;
	private static Connection conn = null;
	
	//private attributes used to make connection
	private String DB_DRIVER = "com.mysql.jdbc.Driver";
	private String DB_URL = "jdbc:mysql://localhost:3306/gamers";
	private String DB_USERNAME = "root";
	private String DB_PASSWORD = "";
	
	/**
	 * constructor
	 */
	private ConnMgr() { }
		
	/**
	 * Get the instance of Connection Manager
	 * @return an instance of ConnMgr
	 */
	public static ConnMgr getInstance() 
	{
		if ( connMgr == null)
		{
			connMgr = new ConnMgr();
		}
		return connMgr;
	}
	
	/**
	 * Retrieve a DB connection and return it to the calling application
	 * 
	 * @return DB connection
	 * @throws ClassNotFoundException 
	 * @throws SQLException 
	 */
	public Connection connect() throws SQLException, ClassNotFoundException 
	{
		if ( conn == null || conn.isClosed() )
			openConnection();

		return conn;	
	}
	
	/**
	 * Retrieve a DB connection from the driver manager 
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	private void  openConnection() throws ClassNotFoundException, SQLException {
		Class.forName(DB_DRIVER);
		conn = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
	}
	
	/**
	 * Close a DB connection
	 * @throws SQLException
	 */
	public void close() throws SQLException 
	{
		if ( conn != null )
			conn.close();
	}
	
}